﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Windows.Input;

namespace ActiveStory.UI
{
    public class SelectionBackElement : FrameworkElement
    {
        private DrawingVisual visual;
        private Boolean isDrawing;
        public Point startPoint;
        public Point endPoint;
        private Brush selectionBrush;
        private Pen selectionPen = new Pen(Brushes.Blue, 1);
        private FrameworkElement container;

        public SelectionBackElement(FrameworkElement container)
        {
            Color color = SystemColors.HighlightColor;
            color.A = 128;
            selectionBrush = new SolidColorBrush(color);
            selectionPen = new Pen(SystemColors.HighlightBrush, 1);
            visual = new DrawingVisual();
            this.AddVisualChild(visual);

            this.container = container;
            container.MouseDown += MouseDownHandler;
            container.MouseMove += MouseMoveHandler;
            container.MouseUp += MouseUpHandler;
        }

        protected override Int32 VisualChildrenCount
        {
            get { return 1; }
        }

        protected override Visual GetVisualChild(Int32 index)
        {
            return visual;
        }

        private void MouseDownHandler(Object sender, MouseButtonEventArgs e)
        {
            startPoint = e.GetPosition(this);
            isDrawing = true;
        }

        private void MouseMoveHandler(Object sender, MouseEventArgs e)
        {
            if (isDrawing && e.LeftButton == MouseButtonState.Pressed)
            {
                Point curEndPoint = e.GetPosition(this);
                DrawSelection(selectionBrush, selectionPen, startPoint, curEndPoint);
            }
        }

        private void MouseUpHandler(Object sender, MouseButtonEventArgs e)
        {
            endPoint = e.GetPosition(this);
            isDrawing = false;
        }

        private void DrawSelection(Brush fill, Pen pen, Point startPoint, Point endPoint)
        {
            Vector vector = endPoint - startPoint;
            if (vector.Length > 10)
            {
                using (DrawingContext dc = visual.RenderOpen())
                {
                    dc.DrawGeometry(fill, pen, new RectangleGeometry(new Rect(startPoint, endPoint)));
                }
            }
        }
    }
}